const gulp = require('gulp')
const sass = require('gulp-sass')
const rename = require('gulp-rename')
const changed = require('gulp-changed')
const watcher = require('gulp-watch')
const chalk = require('chalk')
const nodePath = require('path')

// 自动监听
gulp.task('default', gulp.series(generateWxss))
function generateWxss() {
  watcher(
    [
      'pages/**/*.scss',
      'component/**/*.scss'

    ],
    function (file) {
      if (file.history && file.history[0]) {
        const path = file.history[0]
        if (path.includes('app.scss')) {
          console.log(`开始编译：${chalk.green(path)}`)
          sassToWxss('./', './app.scss')
        } else {
          const arr = path.match(/.*xiaochengxu\\(.*?)\\/)
          if (arr && arr[1]) {
            console.log(`开始编译：${chalk.green(path)}`)
            sassToWxss(arr[1])
          }
        }
      }
    }
  )
}

function sassToWxss(path, src = `${path}/**/*.scss`) {
  return (
    gulp
      .src(src)
      .pipe(
        sass({
          outputStyle: 'expanded',
        })
      )
      .pipe(
        rename((path) => {
          path.extname = '.wxss'
        })
      )
      .pipe(changed(path))
      // 输出目录
      .pipe(gulp.dest(path))
      .pipe(
        rename((parsedPath) => {
          const filePath = nodePath.join(
            __dirname,
            `${path}/${parsedPath.dirname}/${parsedPath.basename}.scss`
          )
          console.log(`编译完成：${chalk.green(filePath)}`)
        })
      )
  )
}
